package com.taotao.common;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;

import net.sf.jxls.transformer.XLSTransformer;

public class ExcelUtils {

	//导出文件 配置的文件夹
	private static final String PREFIX = "jxl/";
	//导出的后缀
	private static String SUFFIX = ".xls" ;
	//文件夹路径
	private static String PATH = null ;
	static{
		PATH = ExcelUtils.class.getClassLoader().getResource("").getPath() ;
	}
	
	public static void exportExcel(ExportParaVo paravo,HttpServletRequest request,HttpServletResponse response){
		//导出文件配置名
		String fileKey = paravo.getFileKey() ;
		//文件绝对路径
		String realPath = PATH + PREFIX + fileKey + SUFFIX ;
		//导出文件默认名字
		String defaultFileName = paravo.getDefaultFileName() + SUFFIX;
		//要导出的数据
		Object data = paravo.getData() ;
		//得到模板转换对象
		XLSTransformer transformer = new XLSTransformer();
		InputStream inputStream = null ;
		try {
			//得到模板流
			inputStream = new FileInputStream(realPath) ;
			//参数对象
			Map<String,Object> beans = new HashMap<String,Object>();
			//模板里定义了items,会遍历 items，和模板对应 
			beans.put("items", data);
			//开始转换，会把beans里的items对象，遍历填充到模板，生成一个文件流
			Workbook hssfworkbook = transformer.transformXLS(inputStream, beans);
			//设置response导出excel的参数
			defaultFileName= new String(defaultFileName.getBytes("GBK"),"ISO-8859-1") ;
			response.setHeader("Content-Disposition", "attachment;filename="+defaultFileName );
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			//把导出的excel文件流，写入response
			hssfworkbook.write(response.getOutputStream());
			response.getOutputStream().flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e) ;
		}finally{
			try {
				if(inputStream!=null){
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e) ;
			}
		}
	}
}
